#include "MineAction.h"

MineAction::MineAction() : BasicAction()
{
}

MineAction* MineAction::clone()
{
	return new MineAction(*this);
}

void MineAction::_onFrame()
{
	if(group == NULL)
		return;
	for ( Unitset::iterator i = group->getUnits()->begin(); i != group->getUnits()->end(); ++i ) {
		// Get a direct pointer to our unit so we do not have to continuously dereference the iterator
		Unit *u = *i;
		if ( u == NULL || !u->exists() )
			continue;

		// Ignore the unit if it has one of the following status ailments
		if ( u->isLockedDown() || u->isMaelstrommed() || u->isStasised() )
			continue;


		// Ignore the unit if it is in one of the following states
		if ( u->isLoaded() || u->isUnpowered() || u->isStuck() )
			continue;

		// Ignore the unit if it is incomplete or busy constructing
		if ( !u->isCompleted() || u->isConstructing() )
			continue;

		// If the unit is a worker unit
		if(u->getType().isWorker()) {
			// if our worker is idle
			if(u->isIdle()) {
				// Order workers carrying a resource to return them to the center,
				// otherwise find a mineral patch to harvest.
				if ( u->isCarryingGas() || u->isCarryingMinerals() ) {
					u->returnCargo();
				}
				else if (!u->getPowerUp()) {  // The worker cannot harvest anything if it
					// is carrying a powerup such as a flag
					// Find the closest mineral patch
					// Declare some variables to help with obtaining the closest unit
					Unit *closest = NULL;
					int   closestDistance = 999999;
					for ( Unitset::iterator m = Broodwar->getMinerals().begin(); m != Broodwar->getMinerals().end(); ++m ) {
						int newDistance = u->getDistance(*m);

						// Continue iterating if the new distance is greater than the old distance
						if ( newDistance >= closestDistance )
							continue;

						// Save our distance information if it is closer
						closestDistance = newDistance;
						closest = *m;
					}

					// If a mineral patch was found
					if ( closest ) {
						// Order our worker to harvest the patch!
						u->gather(closest);

						// Continue iterating other units so we don't interrupt this order and produce unnecessary commands
						continue;
					}
				} // closure: has no powerup
			} // closure: if idle

		}
	}
}

void MineAction::_onActionStart()
{
}

void MineAction::_onActionStop()
{
}